package com.story.modular.app.controller;

import com.story.config.properties.UpyunProperties;
import com.story.core.base.controller.BaseController;
import com.story.core.util.DateUtil;
import com.story.core.util.UriUtil;
import com.story.modular.app.service.UpyunService;
import main.java.com.UpYun;
import main.java.com.upyun.MediaHandler;
import main.java.com.upyun.Result;
import main.java.com.upyun.UpException;
import main.java.com.upyun.UpYunUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Administrator
 * @decription
 * @Date 2018-01-09 11:30
 */
@Controller
@RequestMapping(value = "/file")
public class FileUploadController extends BaseController{

    private static final Logger log = LoggerFactory.getLogger( CloudUploadController.class);

    private static final Long EXPIRE_TIME = 3600L;

    private static final String METHOD = "POST";

    private static final String HTTP_PREFIX = "http://";

    private static final String SP = "/";

    private static final String POINT = ".";

    @Autowired
    private UpyunService upyunService;

    @Autowired
    private UpyunProperties upyunProperties;

    @Autowired
    private UpYun upYun;
    @RequestMapping(method = RequestMethod.POST, path = "/getConfig2")
    @ResponseBody
    public ResponseEntity getConfig2() throws JSONException {
        HttpServletRequest request = super.getHttpServletRequest();
        //视频文件的内容
        String path = request.getParameter("path");
        //图片存放的位置
        String imgName=request.getParameter("imgName");
        //时间位置 从什么开始截图
        String startTime=request.getParameter("startTime");
        //回调地址
        String NOTIFY_URL=request.getParameter("NOTIFY_URL");

        MediaHandler handler = new MediaHandler(upyunProperties.getServerName(), upyunProperties.getUserName(), upyunProperties.getPassword());

        //初始化参数组 Map
        Map<String, Object> paramsMap = new HashMap<String, Object>();

        paramsMap.put(MediaHandler.Params.BUCKET_NAME, upyunProperties.getServerName());
        paramsMap.put(MediaHandler.Params.NOTIFY_URL, NOTIFY_URL);
        paramsMap.put(MediaHandler.Params.ACCEPT, "json");
        paramsMap.put(MediaHandler.Params.SOURCE, path);

        JSONArray array = new JSONArray();

        JSONObject json = new JSONObject();


        json.put(MediaHandler.Params.TYPE, "thumbnail");
        json.put(MediaHandler.Params.AVOPTS, "/o/true/n/1/ss/"+startTime);
        json.put(MediaHandler.Params.RETURN_INFO, "true");
        json.put(MediaHandler.Params.SAVE_AS, SP + upyunProperties.getVideoPath() + SP + DateUtil.getDays() + SP+imgName);

        JSONObject json2 = new JSONObject();

        array.put(json);

        paramsMap.put(MediaHandler.Params.TASKS, array);

        Result result = null;
        try {
            result = handler.process(paramsMap);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (UpException e) {
            e.printStackTrace();
        }

        //String[] ids = handler.getTaskId(result.getMsg());
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("succcess",result);
        return ResponseEntity.ok(map);
    }

    /**
     * 得到配置，生成上传签名
     * @return
     * @throws IOException
     * @throws UpException
     */
    @RequestMapping(method = RequestMethod.POST, path = "/getConfig")
    @ResponseBody
    public ResponseEntity getConfig() throws IOException, UpException {
        HttpServletRequest request = super.getHttpServletRequest();
        String fileType = request.getParameter("fileType");
        String flag = request.getParameter("flag");
        String path = null;
        if("logo".equals(flag)) {
            path = SP + upyunProperties.getImagePath() + SP + DateUtil.getDays() + SP + UUID.randomUUID() + POINT + fileType;
        }
        if("video".equals(flag)) {
            path = SP + upyunProperties.getVideoPath() + SP + DateUtil.getDays() + SP + UUID.randomUUID() + POINT + fileType;
        }
        String uploadUrl = HTTP_PREFIX + upYun.getApiDomain() + SP + upyunProperties.getServerName();

        //生成policy
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("bucket",upyunProperties.getServerName());
        params.put("expiration",DateUtil.format(new Date()).getTime() / 1000 + 3600);
        params.put("save-key",path);
        params.put("date",getRfc1123Time());
        String policy = UpYunUtils.getPolicy(params);

        //生成认证
        String authorization = UpYunUtils.sign(METHOD,getRfc1123Time(),path,upyunProperties.getUserName(),upyunProperties.getPassword(),UpYunUtils.md5(path));

        //得到签名
        String signature = UpYunUtils.getSignature(policy,upyunProperties.getSecretKey());

        String requestUrl = upyunProperties.getDomain();
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("uploadUrl",uploadUrl);
        map.put("authorization",authorization);
        map.put("requestUrl",requestUrl);
        map.put("signature",signature);
        map.put("policy",policy);
        map.put("imgpath",SP + upyunProperties.getVideoPath() + SP + DateUtil.getDays()+SP);
        return ResponseEntity.ok(map);
    }

    /**
     * 后端上传到又拍云
     * @param file
     * @return
     * @throws IOException
     * @throws UpException
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public String upload(@RequestPart("file") MultipartFile file) throws IOException, UpException {
        String filenameExtension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
        InputStream content = file.getInputStream();
        String fileAddr = upyunService.uploadFile(content,filenameExtension);
        return fileAddr;
    }

    /**
     * 得到格林威治时间
     * @return
     */
    private String getRfc1123Time() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone( TimeZone.getTimeZone("GMT"));
        return dateFormat.format(calendar.getTime());
    }
}
